package own.stu.jobgib.playown.netty.pdf_demo.demo1;

import sun.misc.Signal;

import java.util.concurrent.TimeUnit;

/**
 * 对于采用注册 SignalHandler 实现优雅退出的程序，在handle 接口中一定要避免阻塞操作，
 * 否则它会导致已经注册的ShutdownHook无法执行，系统也无法退出.
 */
public class SignalHandlerTest {

    public static void main(String[] args) throws Exception {
        // Signal sig = new Signal("INT");//windows
        Signal sig = new Signal("TERM");//linux
        Signal.handle(sig, (s) -> {
            System.out.println("Signal handle start...");
            try {
//                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Runtime.getRuntime().addShutdownHook(new Thread(() ->
        {
            System.out.println("ShutdownHook execute start...");
            System.out.println("Netty NioEventLoopGroup shutdownGracefully...");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("ShutdownHook execute end...");
        }, ""));
        new Thread(new Runnable() {
            public void run() {
                try {
                    TimeUnit.DAYS.sleep(Long.MAX_VALUE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Daemon-T").start();
    }
}